package com.hula.init;

import com.hula.common.ReleaseConnectionThread;
import org.apache.http.client.HttpClient;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;

import javax.net.ssl.SSLContext;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author liuhe
 * @date 2021/3/25
 * @Description 初始化http连接
 */
public class InitHttpConnection {
    /**
     * 启用连接管理器
     */
    public static PoolingHttpClientConnectionManager connectionManager;
    static {
        LayeredConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = SSLContexts
                    .custom()
                    .loadTrustMaterial(new TrustStrategy() {
                        @Override
                        public boolean isTrusted(X509Certificate[] chain,
                                                 String authType) throws CertificateException {
                            return true;
                        }
                    })
                    .build();
            sslsf = new SSLConnectionSocketFactory(sslContext);
        } catch (Exception e) {
            throw new RuntimeException("httpClient初始化失败");
        }
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory())
                .build();
        connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        //连接池最大连接数
        connectionManager.setMaxTotal(200);
        //同一连接最大并发数
        connectionManager.setDefaultMaxPerRoute(32);
        //启动释放连接线程
        new ReleaseConnectionThread(connectionManager);
    }

    /**
     * 获取httpClient请求
     * @return
     */
    public static HttpClient getHttpClient() {
        return HttpClients.custom()
                .setConnectionManager(connectionManager).build();
    }
}
